package com.android.kmlmrg.services.rest.method;



import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONObject;

import android.app.Application;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

import com.android.kmlmrg.R;
import com.android.kmlmrg.event.RestPhotoEvent;
import com.android.kmlmrg.listener.custom.RestPhotoListener;
import com.android.kmlmrg.model.ApiSession;
import com.android.kmlmrg.model.User;
import com.android.kmlmrg.services.ServiceController;

public class Photo extends AsyncTask<Void, Integer, Bitmap> {
	
	private static final  String LOG_TAG = Photo.class.getName();
	private final static String METHODE_NAME = "/photo";
	private User user;
	private int identifiant;
	private Application vApplication;
	
	
	private static  ArrayList<RestPhotoListener> listeners = new ArrayList<RestPhotoListener>();


	public Photo(Application pApplication , User pUser ) {
		vApplication = pApplication;
		Log.i(LOG_TAG, "START - construct Photo()");

		identifiant = Integer.parseInt(pUser.getIdentifiant());
		user = pUser;
		
		Log.i(LOG_TAG, "END - construct Photo()");
	}
	
	
    protected Bitmap doInBackground(Void... sUrl) {
        try {
        	String vUrl = this.vApplication.getString(R.string.user_endpoint) + METHODE_NAME + "/" + identifiant;
        	
           	ApiSession vApiSession =  ServiceController.getInstance().getApiSession() ;
        	JSONObject vJsonObject = new JSONObject();				
			vJsonObject.put(ApiSession.WSCALLERID, vApiSession.getWsCallerId());
			vJsonObject.put(ApiSession.TIMESTAMP, vApiSession.getTimesTamp());
			vJsonObject.put(ApiSession.HASH, vApiSession.getHash());
			String message = vJsonObject.toString();
        	
        	URLConnection url = new URL(vUrl).openConnection();
        	HttpURLConnection httpcon = (HttpURLConnection) ((new URL(vUrl).openConnection()));
      
            httpcon.setRequestProperty("Content-Type", "application/json");
            httpcon.setRequestProperty("Accept", "application/json");
            httpcon.setRequestMethod("POST");
           
            httpcon.setDoInput(true);
            httpcon.setDoOutput(true);
            httpcon.setFixedLengthStreamingMode(message.getBytes().length);
            httpcon.connect();
  
            
            OutputStream os = new BufferedOutputStream(httpcon.getOutputStream());
            os.write(message.getBytes());
            //clean up
            os.flush();
            
            
            // this will be useful so that you can show a typical 0-100% progress bar
            int fileLength = httpcon.getContentLength();

            // download the file
         
            InputStream input = httpcon.getInputStream();
           
            Bitmap bitmap = BitmapFactory.decodeStream(input);

            os.flush();
            os.close();
            input.close();
            
return bitmap;
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }


    
    

	@Override
	protected void onPostExecute(Bitmap result) {
		RestPhotoEvent vEvent = new RestPhotoEvent(this, Integer.parseInt(user.getIdentifiant()), result);
		fireEvent(vEvent);
		super.onPostExecute(result);
	}


	private void fireEvent( RestPhotoEvent pEvent ){		
		for(RestPhotoListener listener : listeners){
			listener.resultPhotoRequest( pEvent );
		}
	}

	public static void addListener ( RestPhotoListener pListener ){
		listeners.add(pListener);
	}

	public static void removeListener( RestPhotoListener pListener ){
		listeners.remove(pListener);
	}


}
